<template>
  <el-form label-width="120px" :model='SpuInfo' ref="ruleFormRef" :rules="rules">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input placeholder="Spu名称" v-model="SpuInfo.spuName" />
    </el-form-item>
    <el-form-item label="SPU品牌" prop="tmId">
      <el-select placeholder="请选择" v-model="SpuInfo.tmId">
        <el-option :label="trademark.tmName" :value="trademark.id" v-for="trademark in AllTrademarkList"
          :key="trademark.id" />

      </el-select>
    </el-form-item>


    <el-form-item label="SPU描述" prop="description">
      <el-input rows="4" type="textarea" placeholder="SPU描述" v-model="SpuInfo.description" />
    </el-form-item>
    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload v-model:file-list="fileList" :action="`${BASE_URL}/admin/product/upload`" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select :placeholder="`还有${SaleAttrLists.length}项为选择`" v-model="SpuInfo.spuSaleAttr">
        <el-option :label="item.name" :value="item.name" v-for="item in SaleAttrLists" :key="item.id" />

      </el-select>
      <el-button type="primary" :icon="Plus" @click="AddSaleAttr">添加属性</el-button>

      <el-table border style="width: 100% ;margin:20px 0;" :data="SpuInfo.spuSaleAttrList">
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column prop="saleAttrName" label="属性名" width="180" align="center" />
        <el-table-column label="属性值列表 " align="center">
          <template v-slot="{ row, $index }">
            <el-tag v-for="t1 in row.spuSaleAttrValueList" :key="row.id" class="mx-1" closable
              :disable-transitions="false" @close="handleClose(row, $index)">
              {{ t1.saleAttrValueName }}
            </el-tag>
            <el-input v-if="row.inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20" size="small"
              @keyup.enter="handleInputConfirm(row)" @blur="handleInputConfirm(row)" />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              + New Tag
            </el-button>
          </template>

        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template v-slot="{ row, $index }">
            <el-popconfirm title="您真的要删除此属性吗?" @confirm="confirmEvent($index)">
              <template #reference>
                <el-button title="删除属性" type="danger" :icon="Delete" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>

        </el-table-column>
      </el-table>


    </el-form-item>
    <el-form-item>

      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="emits('ShowStatus', ShowStatus.SPU_LIST)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SpuForm"
}
</script>
<script lang="ts" setup>

import { reactive, ref, nextTick, onMounted, computed } from 'vue'


import type { FormInstance, FormRules } from 'element-plus'
import { ElInput } from 'element-plus'
import { ShowStatus } from "./type"
import { reqGetSaleAttr, reqUpdatespuInfo, reqGetAllTrademark, reqgETaDDData, reqspuImageData, reqgetAttrData } from "@/api/product/spu"
import {
  Check,
  Delete,

  Plus
} from '@element-plus/icons-vue'
import { useCategorySelectorStore } from "@/stores/CategoryList"
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])
//控制组件切换的自定义事件
const emits = defineEmits(["ShowStatus",])
const props = defineProps(["spuListdata"])
//13校验规则
const rules = reactive<FormRules>({

  spuName: [
    { required: true, message: '请输入spu名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度至少为1', trigger: 'blur' },
  ],
  tmId: [
    {
      required: true,
      message: '请选择spu品牌',
      trigger: 'change',
    },
  ],
  description: [
    { required: true, message: '请输入SPU描述', trigger: 'blur' },
  ],
  spuImageList: [
    {
      type: 'array',
      required: true,
      message: '请至少输入一张图片',
      trigger: 'change',
    },


  ],
  spuSaleAttrList: [
    { required: true, message: '请选择spu描述', trigger: 'change' },
  ]
})
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const Selector = useCategorySelectorStore()
//图片的action路径前置
const BASE_URL = import.meta.env.VITE_API_URL
//属性值列表的tag标签
const inputValue = ref('')


const InputRef = ref<InstanceType<typeof ElInput>>()
//定义品牌属性
const AllTrademarkList = ref([])
//定义销售属性
const SaleAttrList = ref([])
//2定义一个spu对象
const SpuInfo = reactive({
  description: "",//spu描述
  spuName: '',//spu名称
  tmId: '',//spu品牌
  spuImageList: [],//存储那些图片的路径
  spuSaleAttrList: [],//属性名列表
  spuSaleAttr: '',//销售属性,
  category3Id: 0,
  ...props.spuListdata
})
//12提交表单,在我提交表单的时候也需要校验一下我的属性值
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const saleAttrLis = SpuInfo.spuSaleAttrList
      if (saleAttrLis.length && saleAttrLis.some(item => item.spuSaleAttrValueList.length == 0)) {
        ElMessage.warning('你的销售属性值中有为空白的哦');
        return
      }




      SpuInfo.category3Id = Selector.category3Id
      if (SpuInfo.id) {
        await reqUpdatespuInfo(SpuInfo)
        ElMessage.success('数据更新成功了')
      }
      await reqgETaDDData(SpuInfo);
      ElMessage.success('数据获取成功了'),
        emits('ShowStatus', ShowStatus.SPU_LIST)
    } else {
      console.log('error submit!', fields)
    }
  })
}


//10删除一条属性值
const handleClose = (row, index: number) => {
  console.log(row)
  row.spuSaleAttrValueList.splice(index, 1)
}

const showInput = (row) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
//9失去焦点
const handleInputConfirm = (row) => {

  //11销售的属性值不能输入两个一样的值
  const spuSaleAttrValueList = row.spuSaleAttrValueList;
  if (spuSaleAttrValueList.find(item => {
    return (item.saleAttrValueName == inputValue.value)
  })) {
    ElMessage.warning('不能输入两个一样的属性值')
    row.inputVisible = false;
    inputValue.value = ''
    return
  }



  if (inputValue.value) {

    // dynamicTags.value.push(inputValue.value)
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      isChecked: 0,
      saleAttrName: row.saleAttrName,
      saleAttrValueName: inputValue.value
    })

  }
  row.inputVisible = false;
  inputValue.value = ''
}
//3成功上传之后所触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log(response, uploadFile, 11)
  SpuInfo.spuImageList.push(
    {
      imageName: uploadFile.name,
      imgUrl: response.data
    }

  )

  ruleFormRef.value?.clearValidate(["spuImageList"])
}
//4成功上传之前触发的函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 定义的我的类型数据
  const imageUrlType = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png'];
  if (!imageUrlType.includes(rawFile.type)) {
    // if (rawFile.type) {
    ElMessage.error(' 请上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('请输入正确大小的格式的图片')
    return false
  }
  return true
}
//5移除某个图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  SpuInfo.spuImageList = uploadFiles.map(item => {
    return {
      imageName: item.name,
      imgUrl: item.response ? item.response.data : item.url
    }
  })
}
// 6实现图片的预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//7实现销售属性添加属性
const AddSaleAttr = () => {
  //当选  取一项销售属性时，我的销售属性的值不能为空，要是为空了，就不能添加销售属性

  const spuSaleAttrList = SpuInfo.spuSaleAttrList;
  if (spuSaleAttrList.length && spuSaleAttrList.some(item => item.spuSaleAttrValueList.length == 0)) {
    ElMessage.warning('销售的属性值不能为空');
    return
  }
  //需要在我的销售属性的列表中使用find,find是看我数组中的每一项是啥，返回的就是啥，将我销售属性数组的对象的name与spuInfo的销售属性相同的时候，就找到了哪一项，然后再。id

  const id = SaleAttrList.value.find(Item => Item.name == SpuInfo.spuSaleAttr).id

  SpuInfo.spuSaleAttrList.push({
    inputVisible: false,
    baseSaleAttrId: id,
    saleAttrName: SpuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],

  })
  //删除残留的数据
  SpuInfo.spuSaleAttr = ''

}
//8一个计算销售属性点一个少一个，下面的表格多一下想
const SaleAttrLists = computed(() => {
  return SaleAttrList.value.filter(item => {
    return !SpuInfo.spuSaleAttrList.find(it => {
      return (it.saleAttrName == item.name)
    })
  })
})
//组件已挂账就要请求数据
onMounted(async () => {

  const { id } = SpuInfo;


  //有id的话就是数据回显，要是没有的话便是添加
  if (id) {

    const promises = [reqGetAllTrademark(), reqGetSaleAttr(), reqspuImageData(id), reqgetAttrData(id)]
    const [Trademark, SaleList, spuImageList, SaleAttrListst] = await Promise.all(promises);
    // console.log(spuImageList,SaleAttrList)
    //赋值
    AllTrademarkList.value = Trademark;
    SaleAttrList.value = SaleList;
    SpuInfo.spuImageList = spuImageList;
    console.log(spuImageList)
    SpuInfo.spuSaleAttrList = SaleAttrListst


    fileList.value = spuImageList.map(item => {
      return {
        ...item,
        name: item.imageName,
        url: item.imgUrl,
      }
    })

  } else {

    const [Trademark, SaleList] = await Promise.all([reqGetAllTrademark(), reqGetSaleAttr()])

    //赋值
    AllTrademarkList.value = Trademark;
    SaleAttrList.value = SaleList;
  }



})
//删除一条销售属性
const confirmEvent = (index: number) => {
  SpuInfo.spuSaleAttrList.splice(index, 1)
}
</script>

<style lang="scss" scoped>

</style>